<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="hAdd(1,'0')">添加权限</el-button>
        </div>
        <el-table row-key="id" default-expand-all :data="list" border>
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button v-if="row.type === 1" type="text" @click="hAdd(2,row.id)">添加</el-button>
              <el-button type="text" @click="hEdit(row.id)">编辑</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-dialog :visible.sync="showDialog" title="弹层标题" @closed="hClosed">
      <!-- 表单内容 -->
      <el-form ref="formData" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="权限启用" prop="enVisible">
          <el-switch
            v-model="formData.enVisible"
            active-text="启用"
            active-value="1"
            inactive-text="不启用"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="text-align: right;">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addPermission, delPermission, getPermissionDetail, getPermissionList, updatePermission } from '@/api/permisson'
import { tranListToTreeData } from '@/utils'
export default {
  data() {
    const nameValid = (rule, value, callback) => {
      let codeList = this.originList.filter(item => item.pid === this.formData.pid)
      // console.log(codeList)
      if (this.isEdit) {
        codeList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      codeList = codeList.map(item => item.name)
      codeList.includes(value) ? callback(new Error(value + '已经存在')) : callback()

      callback()
    }
    const codeValid = (rule, value, callback) => {
      let codeList = this.originList

      // console.log(codeList)
      if (this.isEdit) {
        codeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      codeList = codeList.map(item => item.code)
      codeList.includes(value) ? callback(new Error(value + '已经存在')) : callback()
    }
    return {
      list: [],
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '输入不能为空', trigger: 'blur' },
          { validator: nameValid, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '输入不能为空', trigger: 'blur' },
          { validator: codeValid, trigger: 'blur' }

        ]

      },
      isEdit: false,
      originList: []
    }
  },
  created() {
    this.loadPermissions()
  },
  methods: {
    // 获取权限列表
    async loadPermissions() {
      const res = await getPermissionList()
      // console.log(res)
      // 转换为树形结构
      // console.log(res.data)
      this.originList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name: name.trim(), code }))

      this.list = tranListToTreeData(res.data)
    },
    // 点击添加
    hAdd(type, pid) {
      this.isEdit = false
      // console.log(type, pid)
      this.showDialog = true
      this.formData.type = type
      this.formData.pid = pid
    },
    // 点击dialog确定
    async hSubmit() {
      // 兜底校验
      const valid = await this.$refs.formData.validate().catch(e => e)
      if (!valid) return
      try {
        let res = null
        if (this.isEdit) {
          // 编辑发送请求
          res = await updatePermission(this.formData)
        } else {
          // 添加发送请求
          res = await addPermission(this.formData)
        }
        // 提醒用户
        this.$message.success(res.message)
        this.showDialog = false
        this.loadPermissions()
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // 关闭dialog
    hClosed() {
      // 清空表单
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      // 清除表单校验
      // this.formData.clearValidate()
    },
    // 删除
    async hDel(id) {
      const result = await this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      }).catch(e => e)
      if (result !== 'confirm') return
      try {
        const res = await delPermission(id)
        this.$message.success(res.message)
        this.loadPermissions()
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // 点击编辑数据回填
    async hEdit(id) {
      // 设置编辑状态
      this.isEdit = true
      // 显示dialog
      this.showDialog = true
      // 数据回填
      const res = await getPermissionDetail(id)
      // console.log(res)
      this.formData = res.data
    }
  }
}
</script>
